import Api from "../service/serviceApi";
import {clear, localKey} from "./constant";
import router from "../router";
import {error, message, websocketNotify} from "./messageUtil";

const baseWebsocketPath = import.meta.env.VITE_WEBSOCKET_API;
// const baseWebsocketPath = 'ws://localhost:7000';

let webSocket: WebSocket;

const send = (message: MessageDto)=>{
    if(webSocket != null){
        webSocket.send(JSON.stringify(message))
    }
}

const callbacks = {
    //消息回复显示
    getMessage: (messageDto:MessageDto)=>{},
    notify: (messageDto:MessageDto)=>{},
    inviteGroup: (messageDto:MessageDto)=>{},
    requestGroup: (messageDto:MessageDto)=>{},
    addFriendRequest: (messageDto:MessageDto)=>{},
    showNotice: (messageDto:MessageDto)=>{},
    //在线人数展示
    showOnline:(messageDto:MessageDto)=>{},
    //电话接听
    formPhone: (messageDto:MessageDto)=>{},
    //电话挂断
    phoneDown: (messageDto:MessageDto)=>{},
    //RingDown
    RingDown: (messageDto:MessageDto)=>{},
};


const webSocketLink = (userId: String) => {
    const path = baseWebsocketPath + Api.common.websocketPath + userId;

    webSocket = new WebSocket(path);

    let timer: NodeJS.Timer;
    webSocket.onopen = ()=>{
        console.log("链接成功")
        // 开启心跳模式，防止长时间没有信息响应，websocket链接关闭
        timer = setInterval(()=>{
            const ping = {
                type: MessageType.PING
            };
            webSocket.send(JSON.stringify(ping));
        }, 5000)
    };

    webSocket.onclose = (e)=>{
        console.log("关闭链接", e)

        //跳转到登入页面
        router.push({
            name:'login'
        }).then(()=>{
            //跳转页面时会销毁websocket 所以这里不进行清理
            //清除信息
            clear();
            error("请重新登入")
        })

        clearInterval(timer);
    };

    webSocket.onmessage = (event)=>{
        const message:MessageDto = JSON.parse(event.data)
        //如果是服务器端 推送PING信号 说明下线
        if(message.type === MessageType.PING){
            //跳转到登入页面
            router.push({
                name:'login'
            }).then(()=>{
                //跳转页面时会销毁websocket 所以这里不进行清理
                //清除信息
                clear();
            })
            //防止执行后面的方法
            return
        }

        if(message.type === MessageType.TEXT){
            callbacks.getMessage(message);
            callbacks.notify(message);
            return;
        }


        if(message.type === MessageType.INVITE){
            callbacks.inviteGroup(message);
            return;
        }

        if(message.type === MessageType.REQUEST){
            callbacks.requestGroup(message);
            return;
        }

        if(message.type === MessageType.ADDFRIEND){
            callbacks.addFriendRequest(message);
            return;
        }

        if(message.type === MessageType.NOTICE){
            callbacks.showNotice(message);
            return;
        }

        if(message.type === MessageType.ONLINESHOW){
            callbacks.showOnline(message)
            return;
        }

        if(message.type === MessageType.TOPHONE){
            callbacks.formPhone(message)
            return;
        }

        if(message.type === MessageType.HANGPHONE){
            callbacks.phoneDown(message)
            return;
        }

        if(message.type === MessageType.RING){
            callbacks.RingDown(message)
            return;
        }
    }
}

export type MessageDto = {

    //发送人
    sendUserSocketDto:UserDto

    //接收人
    acceptUserSocketDto:UserDto

    //内容
    message:string

    //类型
    type:MessageType

    sessionType:SessionType
}

//用户
export type UserDto = {
    userId: string,
    name: string
}

export enum MessageType{
    PING="PING",

    TEXT="TEXT",

    HTML="HTML",

    INVITE="INVITE",

    REQUEST="REQUEST",

    ADDFRIEND="ADDFRIEND",

    NOTICE="NOTICE",

    ONLINESHOW="ONLINESHOW",

    TOPHONE="TOPHONE",

    HANGPHONE="HANGPHONE",
    RING = "RING"
}

export enum SessionType{
    GROUP="GROUP",

    ALONG="ALONG"
}

export {webSocketLink,send, webSocket, callbacks};